<!-- 仓库 - 工程数据 - 发货计划 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :search.sync="search"
    >
      <template slot-scope="{ row }" slot="status">
        <span v-if="row.status === 0" class="stateWords-success">已完成</span>
        <span v-if="row.status === 1" class="stateWords-danger">未完成</span>
        <span v-if="row.status === 2" class="stateWords-warning">进行中</span>
        <!-- <span v-else class="stateWords-success">已完成</span> -->
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="generationType">
        <span>{{ row.generationType == 'ERP' ? 'ERP同步' : 'MES新增' }}</span>
      </template>
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" :disabled="isDisable" plain @click="handleDelete" v-if="permission.deliveryPlan_delete">删除</el-button>
      </template>
      <!-- 自定义编辑 -->
      <template slot-scope="scope" slot="menu">
        <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          :disabled="scope.row.status !== 1"
          @click="handleEdit(scope.row, scope.index)"
          v-if="permission.deliveryPlan_edit"
        >
          编辑
        </el-button>
        <el-button
          type="text"
          size="small"
          :disabled="scope.row.status !== 1"
          @click="addSequenceNumber(scope.row, scope.index)"
          v-if="permission.deliveryPlan_addSequenceNumber"
        >
          添加序列号
        </el-button>
      </template>
      <!-- 发货产品信息 展示表 -->
      <template slot="infoForm">
        <avue-crud ref="infoCrud" :option="infoOption" :data="infoData" v-model="infoForm" @selection-change="infoSelectionChange">
          <template slot="menuLeft" v-if="lookStatus">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="addProductInfo">新 增</el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" @click="productDelete">删 除 </el-button>
          </template>
          <template slot-scope="{ row }" slot="quantity">
            <el-input-number size="mini" style="width: 200px" v-model="row.quantity" controls-position="right" :min="1" placeholder="请输入需求数量"></el-input-number>
          </template>
          <template slot-scope="{ row }" slot="completedQuantity">
            {{ row.completedQuantity }}
          </template>
          <!-- <template slot-scope="{ row }" slot="isRequireOqc">
            <el-select v-model="row.isRequireOqc" size="mini" style="width: 100px">
              <el-option label="否" :value="false"> </el-option>
              <el-option label="是" :value="true"> </el-option>
            </el-select>
          </template> -->
        </avue-crud>
      </template>
    </avue-crud>
    <el-dialog title="添加序列号" :visible.sync="dialogVisible" append-to-body>
      <avue-form v-if="dialogVisible" ref="sequenceNumberForm" v-model="form" :option="sequenceNumberOption">
        <template slot="info">
          <avue-crud ref="infoCrud" :option="sequenceNumberInfoOption" :data="infoData" v-model="form" @selection-change="infoSelectionChange">
            <template slot="menuLeft">
              <el-button type="primary" size="small" icon="el-icon-plus" @click="addProductInfo">新 增</el-button>
              <el-button type="danger" size="small" icon="el-icon-delete" @click="productDelete">删 除 </el-button>
            </template>
            <template slot-scope="{ row }" slot="startSequenceNumber">
              <el-input size="mini" v-model="row.startSequenceNumber" placeholder="请输入起始"></el-input>
            </template>
            <template slot-scope="{ row }" slot="endSequenceNumber">
              <el-input size="mini" v-model="row.endSequenceNumber" placeholder="请输入结束"></el-input>
            </template>
          </avue-crud>
        </template>
      </avue-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
        <el-button type="primary" size="small" @click="submit"> <i class="el-icon-circle-plus-outline"></i><span>保存</span> </el-button>
      </span>
    </el-dialog>
    <!-- 设备信息 弹框 -->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, partnerLocationList } from '@/api/warehouse/deliveryPlan';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
export default {
  components: {
    CommonModalTemplate,
    GlobalModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    const self = this;
    return {
      pageCode: 'DELIVERY_PLAN',
      initAddress: {
        firstChange: false,
        deliveryAddress: '',
        detailedAddress: ''
      },
      lookStatus: true, // 查看状态
      disabledEdit: false, // 编辑禁选逻辑
      visibile: false,
      form: { detailedAddress: '', deliveryAddress: '' },
      data: [],
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      search: {},
      sequenceNumberInfoOption: {
        selection: true,
        editBtn: false,
        columnBtn: false,
        refreshBtn: false,
        height: 270,
        border: true,
        menuWidth: 100,
        addBtn: false,
        delBtn: true,
        menu: false,
        tip: false,
        column: [
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'name'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          },
          {
            label: '产品类型',
            prop: 'categoryName'
          },
          {
            label: '产品单位',
            prop: 'uom'
          },
          {
            label: '需求数量',
            prop: 'quantity',
            width: 160
            // slot: true
          },
          {
            label: '起始序列号',
            prop: 'startSequenceNumber',
            slot: true
          },
          {
            label: '结束序列号',
            prop: 'endSequenceNumber',
            slot: true
          }
        ]
      },
      dialogVisible: false,
      sequenceNumberForm: {},
      sequenceNumberOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 120,
        group: [
          {
            label: '',
            prop: 'baseInfo',
            column: [
              {
                label: '客户名称',
                prop: 'partnerName',
                type: 'search',
                order: 2,
                disabled: true,
                span: 8,
                rules: [
                  {
                    required: true,
                    message: '请选择客户名称'
                  }
                ],
                appendClick: () => {
                  this.openUserCommonModal({
                    type: 'partnerCode'
                  });
                }
              },
              {
                label: '客户地址',
                prop: 'detailedAddress',
                type: 'select',
                span: 8,
                dicData: [],
                formatter: (row, value, label, column) => {
                  if (row.country && row.province && row.city) {
                    return row.country + row.province + row.city + label;
                  } else {
                    return label;
                  }
                },
                change({ value, column }) {
                  self.changeDetailedAddress(value, column);
                }
              },
              {
                label: '交货日期',
                prop: 'deliveryDate',
                span: 8,
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss',
                type: 'datetime'
              },
              {
                label: 'ASN单号',
                hide: true,
                span: 8,
                prop: 'asnno',
                labelTip: 'ASN（Advanced Shipping Note）指预先发货清单'
              },
              {
                label: '合同/订单号',
                span: 8,
                hide: true,
                prop: 'contractNo'
              }
            ]
          },
          {
            label: '发货产品信息',
            prop: 'deliveryInfo',
            icon: 'el-icon-vertical-bar',
            column: [
              {
                labelWidth: 0,
                label: '',
                prop: 'info',
                span: 24,
                hide: true,
                formslot: true
              }
            ]
          }
        ]
      },
      option: {
        calcHeight: 30,
        height: 'calc(100vh - 440px)',
        selection: true,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        labelWidth: 110,
        menuWidth: 250,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        editBtn: false,
        delBtn: false,
        refreshBtn: true,
        excelBtn: false,
        selection: true,
        columnBtn: false,
        dialogDrag: false, // 开启拖拽功能
        dialogClickModal: false,
        selectable: (row, index) => {
          return row.status === 1 && row.generationType !== 'ERP';
        },
        column: [
          {
            label: '发货单号',
            prop: 'sheetNo',
            search: true,
            order: 1,
            formslot: true,
            props: {
              label: 'name',
              value: 'id'
            },
            dicData: []
          },
          {
            label: '客户编码',
            prop: 'partnerCode'
          },
          {
            label: '客户名称',
            prop: 'partnerName',
            type: 'search',
            searchType: 'input',
            search: true,
            order: 2,
            disabled: true,
            span: 8,
            rules: [
              {
                required: true,
                message: '请选择客户名称'
              }
            ],
            appendClick: () => {
              this.openUserCommonModal({
                type: 'partnerCode'
              });
            }
          },
          {
            label: '客户地址',
            prop: 'detailedAddress',
            type: 'select',
            span: 8,
            dicData: [],
            formatter: (row, value, label, column) => {
              if (row.country && row.province && row.city) {
                return row.country + row.province + row.city + label;
              } else {
                return label;
              }
            },
            change({ value, column }) {
              self.changeDetailedAddress(value, column);
            }
          },
          {
            label: '交货日期',
            prop: 'deliveryDate',
            span: 8,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime'
          },

          {
            label: '单据状态',
            prop: 'status',
            type: 'select',
            search: true,
            order: 3,
            dicUrl: '/api/blade-system/dict/dictionary?code=sheet_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '单据来源',
            prop: 'generationType',
            search: true,
            type: 'select',
            order: 4,
            dicUrl: '/api/blade-system/dict/dictionary?code=sheet_source',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '创建人',
            prop: 'createUserName'
          },
          {
            label: '创建时间',
            prop: 'createTime'
          },
          {
            label: 'ASN单号',
            hide: true,
            span: 8,
            prop: 'asnno',
            labelTip: 'ASN（Advanced Shipping Note）指预先发货清单'
          },
          {
            label: '合同/订单号',
            span: 8,
            hide: true,
            prop: 'contractNo'
          },
          {
            label: '校验参数',
            prop: 'extFields',
            addDisplay: false,
            editDisplay: false,
            hide: true,
            span: 8
          }
        ],
        group: [
          {
            label: '发货产品信息',
            prop: 'equipmentInfo',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                labelWidth: 0,
                label: '',
                prop: 'info',
                span: 24,
                hide: true,
                formslot: true
              }
            ]
          }
        ]
      },
      infoForm: {},
      infoSelectionList: [], // 发货产品信息勾选数据
      infoOption: {
        selection: true,
        editBtn: false,
        height: 270,
        border: true,
        menuWidth: 100,
        addBtn: false,
        delBtn: true,
        menu: false,
        tip: false,
        column: [
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'name'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          },
          {
            label: '产品类型',
            prop: 'categoryName'
          },
          {
            label: '产品单位',
            prop: 'uom'
          },
          {
            label: '需求数量',
            prop: 'quantity',
            width: 250,
            slot: true
          }
          //   {
          //     label: 'OQC检验',
          //     prop: 'isRequireOqc',
          //     slot: true
          //   }
        ]
      },
      infoData: [],
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {} //公用模态框配置信息
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
      let urlQuery = this.$route.query;
      if (urlQuery && urlQuery.no) {
        this.search.sheetNo = decodeURIComponent(urlQuery.no);
      }
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.deliveryPlan_add, false),
        viewBtn: this.vaildData(this.permission.deliveryPlan_view, false),
        delBtn: this.vaildData(this.permission.deliveryPlan_delete, false),
        editBtn: this.vaildData(this.permission.deliveryPlan_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    isDisable() {
      return this.selectionList.some((ele) => {
        return ele.generationType === 'ERP' || ele.status !== 1;
      });
    }
  },
  methods: {
    addSequenceNumber(row, index) {
      this.dialogVisible = true;
      this.form = row;
      getDetail(row.id).then((res) => {
        if (res && res.data.data) {
          let data = res.data.data;
          this.infoData = res.data.data.map((i) => {
            return {
              partMasterId: i.partMasterId,
              id: i.id,
              partNo: i.partMasterCode,
              name: i.partMasterName,
              partModel: i.partMasterModel,
              categoryName: i.categoryName,
              uom: i.uom,
              quantity: i.quantity,
              completedQuantity: i.completedQuantity,
              isRequireOqc: i.isRequireOqc,
              qcTemplateCode: i.qcTemplateCode,
              qcTemplateId: i.qcTemplateId,
              qcTemplateName: i.qcTemplateName,
              startSequenceNumber: i.startSequenceNumber,
              endSequenceNumber: i.endSequenceNumber
            };
          });
        }
      });
    },
    rowSave(row, done, loading) {
      let params = {};
      let flag = this.infoData.some((item, idx) => {
        return !item.quantity;
      });
      if (flag) {
        this.$message({
          type: 'warning',
          message: '需求数量不能为空'
        });
        loading();
        return;
      }
      params.partnerId = row.partnerId;
      params.partnerName = row.partnerName;
      params.partnerCode = row.partnerCode;
      params.asnno = row.asnno;
      params.contractNo = row.contractNo;
      params.deliveryDate = row.deliveryDate;
      params.deliveryAddress = this.initAddress.deliveryAddress;
      params.detailedAddress = this.initAddress.detailedAddress;
      params.sheetType = 'DO';
      params.sheetDetails = this.infoData.map((i) => {
        return {
          partMasterId: i.id,
          uom: i.uom,
          quantity: i.quantity,
          sourceId: i.id,
          sourceNo: i.partNo,
          sourceType: 'DELIVER_PRODUCT',
          qcTemplateCode: this.form.qcTemplateCode,
          qcTemplateName: this.form.qcTemplateName,
          qcTemplateId: this.form.qcTemplateId,
          isRequireOqc: this.form.isRequireOqc
          //   isRequireOqc: i.isRequireOqc
        };
      });
      add(params)
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '新增发货计划成功!'
          });
          done();
        })
        .catch((err) => {
          loading();
        });
    },

    rowUpdate(row, index, done, loading) {
      let params = {};
      let flag = this.infoData.some((item, idx) => {
        return !item.quantity;
      });
      if (flag) {
        this.$message({
          type: 'warning',
          message: '需求数量不能为空'
        });
        loading();
        return;
      }
      params.id = row.id;
      params.partnerId = row.partnerId;
      params.partnerName = row.partnerName;
      params.partnerCode = row.partnerCode;
      params.asnno = row.asnno;
      params.contractNo = row.contractNo;
      params.deliveryDate = row.deliveryDate;
      params.deliveryAddress = this.initAddress.deliveryAddress;
      params.detailedAddress = this.initAddress.detailedAddress;
      params.sheetType = 'DO';
      params.sheetDetails = this.infoData.map((i) => {
        return {
          id: i.partMasterId ? i.id : '',
          partMasterId: i.partMasterId ? i.partMasterId : i.id,
          uom: i.uom,
          quantity: i.quantity,
          sourceId: i.id,
          sourceNo: i.partNo,
          sourceType: 'DELIVER_PRODUCT',
          qcTemplateCode: this.form.qcTemplateCode,
          qcTemplateName: this.form.qcTemplateName,
          qcTemplateId: this.form.qcTemplateId,
          isRequireOqc: this.form.isRequireOqc
          //   isRequireOqc: i.isRequireOqc
        };
      });
      update(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '编辑发货计划成功!'
          });
          done();
        },
        (error) => {
          loading();
        }
      );
    },
    submit() {
      this.$refs.sequenceNumberForm.validate((valid, done) => {
        if (valid) {
          let params = {};
          // let flag = this.infoData.some((item, idx) => {
          //   return !item.quantity;
          // });
          // if (flag) {
          //   this.$message({
          //     type: 'warning',
          //     message: '需求数量不能为空'
          //   });
          //   loading();
          //   return;
          // }
          params.id = this.form.id;
          params.partnerId = this.form.partnerId;
          params.partnerName = this.form.partnerName;
          params.partnerCode = this.form.partnerCode;
          params.asnno = this.form.asnno;
          params.contractNo = this.form.contractNo;
          params.deliveryDate = this.form.deliveryDate;
          params.deliveryAddress = this.initAddress.deliveryAddress;
          params.detailedAddress = this.initAddress.detailedAddress;
          params.sheetType = 'DO';
          params.sheetDetails = this.infoData.map((i) => {
            return {
              id: i.partMasterId ? i.id : '',
              partMasterId: i.partMasterId ? i.partMasterId : i.id,
              uom: i.uom,
              quantity: i.quantity,
              sourceId: i.id,
              sourceNo: i.partNo,
              sourceType: 'DELIVER_PRODUCT',
              qcTemplateCode: this.form.qcTemplateCode,
              qcTemplateName: this.form.qcTemplateName,
              qcTemplateId: this.form.qcTemplateId,
              isRequireOqc: this.form.isRequireOqc,
              startSequenceNumber: i.startSequenceNumber,
              endSequenceNumber: i.endSequenceNumber
            };
          });
          update(params).then(
            () => {
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '添加序列号成功!'
              });
              this.dialogVisible = false;
              done();
            },
            (error) => {
              loading();
            }
          );
        }
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleEdit(row, index) {
      // 获取客户地址
      let detailedAddressColumnIndex = this.option.column.findIndex((col) => col.prop == 'detailedAddress');
      this.option.column[detailedAddressColumnIndex].dicData = [];
      partnerLocationList({
        partnerId: row.partnerId
      }).then((res) => {
        if (res && res.status == 200) {
          let data = res.data.data.map((loc) => {
            return {
              label: loc.location1,
              value: loc.locationId
            };
          });
          this.initAddress.deliveryAddress = row.deliveryAddress;
          this.initAddress.detailedAddress = row.detailedAddress;

          this.$nextTick(() => {
            if (detailedAddressColumnIndex > -1) {
              this.option.column[detailedAddressColumnIndex].dicData = data;
            }
          });
        }
      });
      getDetail(row.id).then((res) => {
        if (res && res.data.data) {
          let data = res.data.data;
          let isEdit = data.some((d) => {
            return Number(d.completedQuantity) > 0;
          });
          this.$nextTick(() => {
            this.infoData = data.map((i) => {
              return {
                partMasterId: i.partMasterId,
                id: i.id,
                partNo: i.partMasterCode,
                name: i.partMasterName,
                partModel: i.partMasterModel,
                categoryName: i.categoryName,
                uom: i.uom,
                quantity: i.quantity,
                completedQuantity: i.completedQuantity
              };
            });
          });
          if (isEdit) {
            this.$message.warning('该发货单存在一个或以上发货的产品，不可编辑');
          } else {
            this.$refs.crud.rowEdit(row, index);
          }
        }
      });
    },
    beforeClose(done) {
      this.initAddress.firstChange = false;
      this.initAddress.deliveryAddress = '';
      this.initAddress.detailedAddress = '';
      done();
    },
    beforeOpen(done, type) {
      this.infoData = [];
      //查看 时 传递行信息
      if (['view'].includes(type)) {
        this.form.extFields = String(this._get(JSON.parse(this.form.extFields) || {}, 'busNo', ''));
        getDetail(this.form.id).then((res) => {
          if (res && res.data.data) {
            let data = res.data.data;
            this.infoData = res.data.data.map((i) => {
              return {
                partMasterId: i.partMasterId,
                id: i.id,
                partNo: i.partMasterCode,
                name: i.partMasterName,
                partModel: i.partMasterModel,
                categoryName: i.categoryName,
                uom: i.uom,
                quantity: i.quantity,
                completedQuantity: i.completedQuantity,
                isRequireOqc: i.isRequireOqc,
                qcTemplateCode: i.qcTemplateCode,
                qcTemplateId: i.qcTemplateId,
                qcTemplateName: i.qcTemplateName
              };
            });
          }
        });
      }
      if (['add', 'edit', 'view'].includes(type)) {
        this.defaults.sheetNo.display = false;
        this.defaults.partnerCode.display = false;
        this.defaults.status.display = false;
        this.defaults.generationType.display = false;
        this.defaults.createUserName.display = false;
        this.defaults.createTime.display = false;
      }
      // 查看时隐藏设备信息 操作列
      if (['view'].includes(type)) {
        this.defaults.partnerName.type = 'input';
        this.lookStatus = false;
      } else {
        this.defaults.partnerName.type = 'search';
        this.lookStatus = true;
      }
      if (['view', 'edit'].includes(type)) {
        this.infoOption.column = [
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'name'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          },
          {
            label: '产品类型',
            prop: 'categoryName'
          },
          {
            label: '产品单位',
            prop: 'uom'
          },
          {
            label: '需求数量',
            prop: 'quantity',
            width: 250,
            rules: [
              {
                required: true,
                message: '请输入需求数量',
                trigger: 'blur'
              }
            ],
            slot: true
          },
          {
            label: '已发货数量',
            prop: 'completedQuantity'
          }
        ];
      } else {
        this.infoOption.column = [
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'name'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          },
          {
            label: '产品类型',
            prop: 'categoryName'
          },
          {
            label: '产品单位',
            prop: 'uom'
          },
          {
            label: '需求数量',
            prop: 'quantity',
            width: 250,
            slot: true
          }
        ];
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 客户信息
        case 'partnerCode':
          this.modalName = 'partnerCodeModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择客户信息（双击进行选择）',
            url: '/api/mes-admin/customer/page',
            // url: '/api/mes-admin/partner/page',
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'PARTNER'
          };
          break;
        // 产品
        case 'xzcp':
          this.modalName = 'xzcpModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择产品信息',
            url: '/api/mes-admin/part-master/page',
            isPage: true,
            query: {
              // partType: 'PRODUCT'
            },
            rowSelectionType: 'multiple',
            menuWidth: 100,
            templateName: 'PARTMASTER'
          };
          break;
        default:
          break;
      }
    },
    changeDetailedAddress(value, column) {
      if (this.initAddress.firstChange) {
        let { dicData } = column;
        if (dicData && dicData.length > 0 && value) {
          this.initAddress.detailedAddress = dicData.filter((dic) => dic.value == value)[0].label;
        } else {
          this.initAddress.detailedAddress = '';
        }
        this.initAddress.deliveryAddress = value;
      }
      this.initAddress.firstChange = true;
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partnerCodeModal':
          this.form.partnerId = this._get(rowData, 'id', '');
          this.form.partnerName = this._get(rowData, 'name', '');
          this.form.partnerCode = this._get(rowData, 'partnerNo', '');
          this.form.qcTemplateName = this._get(rowData, 'qcTemplateName', '');
          this.form.qcTemplateCode = this._get(rowData, 'qcTemplateCode', '');
          this.form.qcTemplateId = this._get(rowData, 'qcTemplateId', '');
          this.form.isRequireOqc = this._get(rowData, 'oqcRequired', '');
          this.initAddress.deliveryAddress = this.form.deliveryAddress = ''; // 地址id
          this.initAddress.detailedAddress = this.form.detailedAddress = ''; // 地址名称

          if (rowData.locationLists && rowData.locationLists.length > 0) {
            this.initAddress.deliveryAddress = this.form.deliveryAddress = rowData.locationLists[0].id;
            this.initAddress.detailedAddress = this.form.detailedAddress = rowData.locationLists[0].location1;

            let data = rowData.locationLists.map((loc) => {
              return {
                label: loc.location1,
                value: loc.id
              };
            });
            let detailedAddressColumnIndex = this.option.column.findIndex((col) => col.prop == 'detailedAddress');
            this.$nextTick(() => {
              if (detailedAddressColumnIndex > -1) {
                this.option.column[detailedAddressColumnIndex].dicData = data;
              }
            });
          }
          this.initAddress.firstChange = false;
          console.log(this.form, 'form');
          break;
        case 'xzcpModal':
          let data = rowData
            .filter((row) => !this.infoData.map((info) => (info.partMasterId ? info.partMasterId : info.id)).includes(row.id))
            .map((d) => {
              return d;
            });
          this.infoData = this.infoData.concat(data);
          this.visibile = false;
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    // 新增产品
    addProductInfo() {
      this.openUserCommonModal({
        type: 'xzcp'
      });
    },
    infoSelectionChange(list) {
      this.infoSelectionList = list;
    },
    // 删除产品
    productDelete() {
      if (this.infoSelectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let ids = this.infoSelectionList.map((list) => list.id);
        this.infoData = this.infoData.filter((info) => !ids.includes(info.id));
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      });
    }
  }
};
</script>
